package com.skillworld.webapp.model.item;

import java.util.List;
import java.util.Set;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.stereotype.Repository;

import com.skillworld.webapp.model.bag.Bag;
import com.skillworld.webapp.model.bag.ItemRecord;
import com.skillworld.webapp.model.gamemap.GameMap;
import com.skillworld.webapp.model.item.Item;
import com.skillworld.webapp.model.item.ItemDao;
import com.skillworld.webapp.model.util.dao.GenericDaoHibernate;

import es.udc.pojo.modelutil.exceptions.InstanceNotFoundException;

@Repository("ItemDao")
public class ItemDaoHibernate extends GenericDaoHibernate<Item,Long> implements ItemDao {
    
    public Item findByCode(String code) throws InstanceNotFoundException
    {
        Item item =(Item) 
            getSession().createQuery("SELECT it FROM Item it " +
                                     "WHERE it.code = :code")
                             .setParameter("code", code)
                             .uniqueResult();
        if (item == null)
        { throw new InstanceNotFoundException(code, Item.class.getName()); }
        
        return item;
    }

    public Item getCasinoItem()
    {
        try
        {
            return findByCode(Item.CASINO_ITEM_CODE);
        }
        catch(InstanceNotFoundException e)
        {
            // Change to something like "ImpossibleHappensException"
            throw new RuntimeException(e);
        }
    }
    
    
    
    /********************************************************/
    
    public void giftCasinoItemBatch()
    {
        Transaction tx = null;
        String hqlCasino = null;
        //
        
        tx = this.getSession().beginTransaction();

        //hqlCasino = " DELETE FROM ItemRecord ir"
        //            +" WHERE ir.expirationDate < CURRENT_DATE()";
        
        
        //"insert into ItemRecord (id, name) select c.id, c.name from Customer c where ...";
               
        //this.getSession().createQuery(hqlCasino).executeUpdate();
        tx.commit();
    }
    
    public void removeOutdatedItemsBatch()
    {
        Transaction tx = null;
        String hqlRemove = null;
        //
        
        tx = this.getSession().beginTransaction();

        hqlRemove = " DELETE FROM ItemRecord ir"
        		    +" WHERE ir.expirationDate < CURRENT_DATE()";
               
        this.getSession().createQuery(hqlRemove).executeUpdate();
        tx.commit();
    }
    
}
